<template>
  <cml-module-item
    :title="titleText"
    :titleMore="titleMore"
    v-bind="$attrs"
    v-on="$listeners"
  >
    <a-switch
      size="small"
      :disabled="false"
      :loading="rloading"
      :checked="isStart"
      @change="change($event, true)"
    />
    <template v-slot:detail>
      <voice-recognize-more></voice-recognize-more>
    </template>
  </cml-module-item>
</template>

<script>
import CmlModuleItem from '../../cml-module-item'
import VoiceRecognizeMore from './morePanel'
import { Switch } from 'ant-design-vue'
import EventBus from '@/assets/js/app/cmlpanel/util/bus.js'
import * as anov from 'anov-core'
import aiMediaCheck from '../../../util/aiMediaCheck'

export default {
  name: 'VoiceRecognize',
  inheritAttrs: false,
  components: {
    ASwitch: Switch,
    CmlModuleItem,
    VoiceRecognizeMore
  },
  model: {},
  props: {},
  data() {
    return {
      rloading: false, //启动加载状态
      hasOpened: false,
      byUser: false
    }
  },
  computed: {
    ...anov.voiceRecognizeServer.mapState(['isStart', 'iatType']),
    ...anov.envServer.mapState(['audioStatus']),
    titleText() {
      return this.$t('cmlpanel.recognition')
    },
    titleMore() {
      return this.$t('cmlpanel.recognition')
    }
  },
  watch: {
    isStart(v, ov) {
      this.change(v)
      //根据开启/关闭状态进行提示
      this.podcast(v)
    },
    async iatType(v) {
      if(this.isStart && v == 'default') {
        let url = 'https://lh3.googleusercontent.com/kPZzK2-bZOssxxI3us3MmJZumwwbX_BhsR9Rs4M0CWnRkCwCl-JsaIS7uRL7Csl28mg=s180-rw'
        let extranet = await this.checkWebSiteOnline(url)
        if(this.isStart && !extranet ) {
          app.msg({
            type: 'error',
            content: '网络错误，请确保连接到远程服务器。'
          })
          anov.voiceRecognizeServer.stop()
        }

      }
    }
  },
  created() {},
  mounted() {
    //初始化状态
    // this.isStart && this.change(this.isStart)
    const eventName = 'voiceReconginzeStateChange'
    app.envServer.addEventListener('offLine', () => {
      if (this.isStart) {
        app.msg({
          type: 'error',
          content: '网络错误，请确保连接到远程服务器。'
        })
        anov.voiceRecognizeServer.stop()
      }
    })
    anov.voiceRecognizeServer.addEventListener('onStart', () => {
      this.rloading = false
      if (!this.hasOpened) {
        this.$result({ anchor: '#app' })
        this.hasOpened = true
      }
      setTimeout(() => {
        aiMediaCheck.audioUsable()
      }, 10)
      EventBus.$emit(eventName, 'start')
    })
    anov.voiceRecognizeServer.addEventListener('onSoundStart', () => {
      EventBus.$emit(eventName, 'soundstart')
    })
    anov.voiceRecognizeServer.addEventListener('onResult', (e) => {
      EventBus.$emit(eventName, 'result', e.result)
    })
    anov.voiceRecognizeServer.addEventListener('onResultMatch', (e) => {
      let cmd = e.result
      //扩展兼容 如果有注册exec 先执行,
      cmd.exec && cmd.exec(anov.actionServer.getCurrentContext(), cmd.params)
      //如果有动作 则执行动作
      cmd.action && anov.actionServer.exec(cmd.action, cmd.params)
      EventBus.$emit(eventName, 'result', cmd)
    })
    anov.voiceRecognizeServer.addEventListener('onStop', () => {
      EventBus.$emit(eventName, 'abort')
      this.$result.close()
      this.hasOpened = false
    })
    anov.voiceRecognizeServer.addEventListener('onError', (e) => {
      this.onError(e)
      EventBus.$emit(eventName, 'abort')
      this.$result.close()
      this.hasOpened = false
      this.setAudioIsAvailable(false)
    })

    anov.voiceRecognizeServer.addEventListener('readyStart', (e) => {
      this.change(true, true)
    })
  },
  methods: {
    ...anov.envServer.mapMutations(['setAudioStatus', 'setAudioIsAvailable']),
    change(isStart, byUser) {
      this.byUser = byUser === true ? byUser : this.byUser
      if (isStart == this.isStart) {
        this.byUser = false
        return
      }
      let flag = app.envServer.localNetwork.connected
      if (!flag) {
        app.msg({
          type: 'error',
          content: '网络错误，请确保连接到远程服务器。'
        })
        return
      }

      let params = {
        type: this.type,
        msg: this.$t('cmlpanel.recognition'),
        //确认开启弹框确认按钮回调
        okCallback: () => {},
        //确认开启弹框取消按钮回调
        cancelCallback: () => {
          this.rloading = false
        },
        //正常开启回调
        startCallback: async () => {
          // this.startCallback()
          this.rloading = isStart
          //在类型为默认时先判断是否可以连接外网，若不可以则直接不启动
          if (this.iatType == 'default') {
            let url =
              'https://lh3.googleusercontent.com/kPZzK2-bZOssxxI3us3MmJZumwwbX_BhsR9Rs4M0CWnRkCwCl-JsaIS7uRL7Csl28mg=s180-rw'
            let extranet = await this.checkWebSiteOnline(url)
            if (!extranet) {
              app.msg({
                type: 'error',
                content: '网络错误，请确保连接到远程服务器。'
              })
              this.rloading = false
              return
            }
          }

          anov.voiceRecognizeServer.start()
        }
      }
      if (isStart) {
        aiMediaCheck.getAudioStatus({ ...params })
      } else {
        //关闭
        anov.voiceRecognizeServer.stop()
        this.rloading = isStart
      }
    },
    onError(e) {
      setTimeout(() => {
        this.rloading = false
      }, 10)
      app.msg({ type: 'error', content: e.result })
    },
    podcast(isStart) {
      let msg =
        this.titleText +
        (isStart ? this.$t('cmlpanel.start') : this.$t('cmlpanel.stop'))
      anov.voiceFeedbackServer.speak(msg)
      app.msg({ type: 'info', content: msg })
      anov.voiceRecognizeServer.addInfo(msg)
    },
    checkWebSiteOnline(url) {
      this.isOnline = -1
      let time = 0
      let img = new Image()
      img.onload = () => {
        this.isOnline = 1
      }

      img.onerror = () => {
        this.isOnline = 0
      }

      img.src = url + '?' + Math.random()
      return new Promise((resolve, reject) => {
        let interval = setInterval(() => {
          if (this.isOnline == 1) {
            clearInterval(interval)
            resolve(true)
          } else if (this.isOnline == 0) {
            clearInterval(interval)
            resolve(false)
          } else {
            if (time < 3) {
              time++
            } else {
              clearInterval(interval)
              resolve(false)
            }
          }
        }, 1000)
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
